package com.lqg.bookLibrary.common.securityImpl;

import com.alibaba.fastjson2.JSON;
import com.lqg.bookLibrary.common.core.domain.JsonResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理匿名用户访问无权限资源时的异常,未登录，或者登录状态过期失效
 * */
@Component
public class CustomizeAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                         AuthenticationException e) throws IOException, ServletException {
        // result = ResultTool.fail(ResultCode.USER_NOT_LOGIN);
        JsonResult jsonResult = JsonResult.error("未登录!","error");
        String output = JSON.toJSONString(jsonResult);;
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(output);
        //httpServletResponse.getWriter().write(JsonResult.fail("未登录!").toString());
    }
}
